package com.itstudio.portal.controller;

import cn.hutool.core.io.IoUtil;
import com.itstudio.portal.entity.RestResponse;
import com.itstudio.portal.entity.dto.AddressDetailDto;
import com.itstudio.portal.entity.dto.IndusDetailDto;
import com.itstudio.portal.enums.HttpCodeEnum;
import com.itstudio.portal.exception.SystemException;
import com.itstudio.portal.service.DictRegionService;
import com.itstudio.portal.service.IndustryService;

import com.itstudio.portal.utils.PathUtils;
import org.apache.ibatis.annotations.Param;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/api/common")
public class CommonController {

    @Value("${upload.path}")
    private String path;

    @Value("${upload.profile}")
    private String profile;

    @Value("${upload.fileType}")
    private String[] fileType;

    @Autowired
    private FileStorageService fileStorageService;//注入实列

    @Autowired
    private DictRegionService dictRegionService;

    @Autowired
    private IndustryService industryService;
    /**
     * 通用上传请求（单个）
     */
    /*@PostMapping("/upload")
    public RestResponse uploadFile(@RequestParam("file")MultipartFile file)
    {
        try
        {
            //做个文件的校验
            fileVerification(file);
            //指定oss保存文件路径dkd-images/ 2024/06/19/文件名
            String objectName= LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))+ "/";
            //上传图片 返回文件信息
            FileInfo fileInfo=fileStorageService.of(file).setPath(objectName).upload();

            Map map=new HashMap<String,String>();

            map.put("url", fileInfo.getUrl());
            map.put("fileName", fileInfo.getUrl());
            map.put("newFileName", fileInfo.getUrl());//注意这里的值需要改为Url,因为前端的访问地址会做一个判断,如果一个http开头就直接显示此图片
            map.put("originalFilename", file.getOriginalFilename());
            return RestResponse.success(map);
        }
        catch (Exception e)
        {
            return RestResponse.failure(500,e.getMessage());
        }
    }*/
    @PostMapping("/upload")
    public RestResponse uploadFile(@RequestPart("file")MultipartFile file)
    {
        try{
            boolean flag = false;
            for(String type : fileType)
                //判断文件类型
                if(file.getOriginalFilename().endsWith(type))
                    flag = true;
            if(!flag) throw new SystemException(HttpCodeEnum.FILE_TYPE_ERROR);
            String imgPath = PathUtils.imgPath(path,file.getOriginalFilename());
            long copySize = IoUtil.copy(file.getInputStream(),
                    new FileOutputStream(path + "/"+ imgPath),
                    IoUtil.DEFAULT_BUFFER_SIZE);
            if(!(copySize > 0)) return RestResponse.failure(400,"文件上传失败");
            return RestResponse.success(profile + "/" + imgPath);
        } catch (IOException e) {
            return RestResponse.failure(400,"文件上传失败");
        }
    }



   /* @PostMapping("/uploads")
    public RestResponse uploadFiles(@RequestParam("uploadFile") List<MultipartFile> files){


        try {


            // 指定oss保存文件路径格式：dkd-images/yyyy/MM/dd/
            String objectNamePrefix = "dkd-images/" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";

            List<String> urls = new ArrayList<>();
            List<String> fileNames = new ArrayList<>();
            List<String> newFileNames = new ArrayList<>();
            List<String> originalFilenames = new ArrayList<>();

            for (MultipartFile file : files) {

                //提交之前做个文件安全校验
                fileVerification(file);

                // 上传图片 返回文件信息
                FileInfo fileInfo = fileStorageService.of(file).setPath(objectNamePrefix).upload();

                urls.add(fileInfo.getUrl());
                newFileNames.add(fileInfo.getUrl()); // 注意这里的值需要改为Url，因为前端的访问地址会做一个判断，如果一个http开头就直接显示此图片
                originalFilenames.add(file.getOriginalFilename());
            }

            Map<String, List<String>> map = new HashMap<>();
            map.put("urls", urls);
            map.put("fileNames", fileNames);
            map.put("newFileNames", newFileNames);
            map.put("originalFilenames", originalFilenames);

            return RestResponse.success(map);
        } catch (Exception e) {
            return RestResponse.failure(500, e.getMessage());
        }
    }*/

    @PostMapping("/uploads")
    public RestResponse uploadFiles(@RequestPart("files") List<MultipartFile> files){

        try{
            List<String> urls = new ArrayList<>();
            //判断文件类型
            for(MultipartFile file : files){
                boolean flag = false;
                for(String type : fileType)
                    //判断文件类型
                    if(file.getOriginalFilename().endsWith(type))
                        flag = true;
                if(!flag) throw new SystemException(HttpCodeEnum.FILE_TYPE_ERROR);
                String imgPath = PathUtils.imgPath(path,file.getOriginalFilename());
                long copySize = IoUtil.copy(file.getInputStream(),
                        new FileOutputStream(path + "/"+ imgPath),
                        IoUtil.DEFAULT_BUFFER_SIZE);
                if(!(copySize > 0)) return RestResponse.failure(400,"文件上传失败");
                urls.add(profile + "/" + imgPath);
            }
            return RestResponse.success(urls);
        } catch (IOException e) {
            return RestResponse.failure(400,"文件上传失败");
        }
    }


    /**
     * 获取服务器URL
     */
    private String getServerUrl() {
        // 这里可以根据实际情况调整服务器URL
        return "http://localhost:8080";
    }


    @GetMapping("/region/{parentCode}")
    public RestResponse getRegionList(@PathVariable Long parentCode) {
        return RestResponse.success(dictRegionService.getRegionTree(parentCode));
    }

    @GetMapping("/industry/{parentId}")
    public RestResponse getIndustryList(@PathVariable String parentId) {
        return RestResponse.success(industryService.getIndustryTree(parentId));
    }

    @GetMapping("/industry/search/{name}")
    public RestResponse getIndustriesForName(@PathVariable String name) {
        return RestResponse.success(industryService.getIndustriesForName(name));
    }

    /**
     * 根据前台传入过来的代码返回行业名称
     * @param indusDetailDto
     * @return
     */
    @PostMapping("/detail")
    public RestResponse industryDetailName(@RequestBody IndusDetailDto indusDetailDto){

        return industryService.getIndustryName(indusDetailDto);


    }


    /**
     * 根据前台传过来的代码返回地址名称
     * @param
     * @throws IOException
     */

    @PostMapping("/addressDeatil")
    public RestResponse getAddressDetail(@RequestBody AddressDetailDto addressDetailDto){
        return dictRegionService.getAddressDetail(addressDetailDto);
    }

    //文件类型校验
    public void fileVerification(MultipartFile file) throws IOException {
        // 文件大小检查
        if (file.getSize() > 10 * 1024 * 1024) { // 最大10MB

            throw new SystemException(HttpCodeEnum.FILE_SIZE_EXCEED_LIMIT);
        }

        // 文件类型检查
        String contentType = file.getContentType();
        List<String> allowedTypes = Arrays.asList("image/jpeg", "image/png", "image/gif","application/pdf");
        if (!allowedTypes.contains(contentType)) {
            throw new SystemException(HttpCodeEnum.INVALID_FILE_TYPE);
        }

        // 文件名检查
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !(originalFilename.endsWith(".jpg") || originalFilename.endsWith(".png") || originalFilename.endsWith(".gif")||originalFilename.endsWith(".pdf"))) {
            throw new SystemException(HttpCodeEnum.ILLEGAL_FILENAME);
        }

        // MIME类型检查
        String actualFileType = Files.probeContentType(Paths.get(file.getOriginalFilename()));
        if (!allowedTypes.contains(actualFileType)) {
            throw new SystemException(HttpCodeEnum.FILE_MIME_TYPE_MISMATCH);
        }
    }

}
